<%--
  Created by IntelliJ IDEA.
  User: brss
  Date: 2017/8/5
  Time: 10:26
  To change this template use File | Settings | File Templates.
  本页作为一个模版，供：新增文章、修改文章、编辑草稿3个地方同时使用
  实现方法：
    1.请求路径：
        新增文章：/admin/adminArticleForm?type=new
        修改文章/修改草稿：/admin/adminArticleForm?type=edit&id=1
    2.服务器Springmvc收到后，根据不同的请求，调用不同的Service，返回不同的model
    3.页面拿到服务器返回的model，把数据用js插入到页面中即可。
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>添加博文</title>
</head>
<body>
<!-- 选择分类的对话框 -->
<div class="modal fade" id="selectCategoryModal" tabindex="-1" role="dialog" aria-labelledby="selectCategoryModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="selectCategoryModalLabel">选择分类</h4>
            </div>
            <div class="modal-body">
                <table class="table table-bordered table-hover" id="categoryTable"></table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="confirmSeleCategory">确认</button>
            </div>
        </div>
    </div>
</div>
<!-- 选择标签的对话框 -->
<div class="modal fade" id="selectTagModal" tabindex="-1" role="dialog" aria-labelledby="selectTagModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="selectTagModalLabel">选择标签</h4>
            </div>
            <div class="modal-body">
                <table class="table table-bordered table-hover" id="tagTable"></table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="confirmSeleTag">确认</button>
            </div>
        </div>
    </div>
</div>
<div class="panel-group">
    <div class="panel panel-primary">
        <div class="panel-heading">
            新增博文
        </div>

        <form method="post" id="articleForm">
            <div class="form-group">
                <input type="hidden" id="articleId" value="${articleId}">
                <label>文章标题</label>
                <input type="text" class="form-control" name="title" id="title">
            </div>
            <div class="form-group">
                <label>文章摘要</label>
                <input type="text" class="form-control" name="summary" id="summary">
            </div>
            <div class="form-group">
                <!-- Button trigger modal -->
                <button type="button" class="btn btn-primary btn-lg" data-toggle="modal"
                        data-target="#selectCategoryModal">
                    选择分类
                </button>
                <span id="alreadySelectCategory">已选择的项：</span>
            </div>
            <div class="form-group">
                <!-- Button trigger modal -->
                <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#selectTagModal">
                    选择标签
                </button>
                <span id="alreadySelectTag">已选择的项：</span>
            </div>
            <label>文章内容</label>
            <textarea id="TextArea1" cols="20" rows="2" class="ckeditor"></textarea>

            <div class="form-group">
                <button type="button" class="btn btn-primary" id="draftArticleFormBtn">存草稿</button>
                <button type="button" class="btn btn-primary" id="submitArticleFormBtn">提交</button>
            </div>
        </form>
        <div class="panel-footer"><!-- panel的foot -->
            <%--这是panel的footer--%>
        </div><!-- end of panel-footer -->
    </div><!-- end of panel -->
</div>

<!-- 先把内容写入到div中，再用js代码获取里面的文本，就能转换为字符串了，有换行什么的也不怕了。 -->
<div id="4ckeditorContent" style="display: none">${key.content}</div>

<script>
    $(function () {
        //初始化富文本编辑器
        CKEDITOR.replace('TextArea1', {extraPlugins: 'codesnippet', codeSnippet_theme: 'zenburn'}
        );
        CKEDITOR.on('instanceReady', function (e) {
            //ckeditor加载完成后的回调函数
            //向表单中写入数据
            $("#title").val("${key.title}");
            $("#summary").val("${key.summary}");
            $("#alreadySelectCategory").text("${key.categoryId}");
            categoryId = "${key.categoryId}";
            $("#alreadySelectTag").text("${key.tagIds}");
            tagIds = "${key.tagIds}";
            CKEDITOR.instances.TextArea1.setData($("#4ckeditorContent").html());

        });
    });
    //点击时启动分类的模态对话框
    $('#selectCategoryModal').on('shown.bs.modal', function () {
        //$('#myInput').focus()
    });
    //点击时启动标签的模态对话框
    $('#selectTagModal').on('shown.bs.modal', function () {
        //$('#myInput').focus()
    });
    //初始化分类表格
    $('#categoryTable').bootstrapTable({
        pageSize: 10,
        pagination: true,//设置为 true 会在表格底部显示分页条
        sidePagination: 'server',//设置在哪里进行分页，可选值为 'client' 或者 'server'。设置 'server'时，必须设置 服务器数据地址（url）或者重写ajax方法
        clickToSelect: true,
        url: '/category/list',
        columns: [{
            checkbox: true
        }, {
            field: 'categoryId',
            title: 'ID编号'
        }, {
            field: 'categoryName',
            title: '分类名称'
        }, {
            field: 'categoryDescription',
            title: '分类说明'
        },]
    });
    //Table表格初始化，加载路径等设置
    $('#tagTable').bootstrapTable({
        pageSize: 10,
        pagination: true,//设置为 true 会在表格底部显示分页条
        sidePagination: 'server',//设置在哪里进行分页，可选值为 'client' 或者 'server'。设置 'server'时，必须设置 服务器数据地址（url）或者重写ajax方法
        clickToSelect: true,
        url: '/tag/list',
        columns: [{
            checkbox: true
        }, {
            field: 'tagId',
            title: 'ID编号'
        }, {
            field: 'tagName',
            title: '标签名称'
        }, {
            field: 'tagDescription',
            title: '标签说明'
        },]
    });
    //选择的分类id字符串
    var categoryId = "";
    //获取选择了哪些分类。
    $("#confirmSeleCategory").click(function (e) {
        $("#alreadySelectCategory").text("已选择的项：");
        categoryId = "";
        //获取到你选择了哪些行（数组 ， 里面装的对象）
        var arr = $('#categoryTable').bootstrapTable('getSelections');
        if (arr.length != 1) {
            alert("只能选择一项");
            return;
        }
        //把已经选择的项目显示到页面中
        var categoryName = "";
        categoryName += arr[0]['categoryName'];
        //生成最终向后台提交的id字符串
        categoryId += arr[0]['categoryId'];
        $("#alreadySelectCategory").append(categoryName);
        //隐藏模态框
        $('#selectCategoryModal').modal('hide');
    });
    //选择的标签id字符串
    var tagIds = ",";
    //获取选择了哪些标签。
    $("#confirmSeleTag").click(function (e) {
        $("#alreadySelectTag").text("已选择的项：");
        tagIds = ",";
        //获取到你选择了哪些行（数组 ， 里面装的对象）
        var arr = $('#tagTable').bootstrapTable('getSelections');
        if (arr.length == 0) {
            alert("请选择一项");
            return;
        }
        //把已经选择的项目显示到页面中
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i]['tagName'] + ",";
            //生成最终向后台提交的ids字符串
            tagIds += arr[i]['tagId'] + ",";
        }
        str = str.substring(0, str.length - 1);
        $("#alreadySelectTag").append(str);
        //隐藏模态框
        $('#selectTagModal').modal('hide');
    });
    //提交表单---发布文章
    $("#submitArticleFormBtn").click(function (e) {
        //验证表单是否有效
        var bootstrapValidator = $('#articleForm').data('bootstrapValidator');
        //手动触发验证
        bootstrapValidator.validate();
        if(!bootstrapValidator.isValid())
            return;
        if(categoryId.length==0){
            alert("请选择分类！")
            return;
        }else if(tagIds.length==1){
            alert("请选择标签！")
            return;
        }else if(CKEDITOR.instances.TextArea1.getData().length==0){
            alert("请输入文章的内容！")
            return;
        }
        $.post("${submitUrl}",
            {
                articleId: $("#articleId").val(),
                summary: $('#summary').val(),
                title: $('#title').val(),
                categoryId: categoryId,
                tagIds: tagIds,
                content: CKEDITOR.instances.TextArea1.getData(),//TextArea1是放这个编辑器的标签的id
            },
            function (data) {
                data = $.parseJSON(data);
                alert(data.msg);
            });
    });
    //提交表单---保存草稿
    $("#draftArticleFormBtn").click(function (e) {
        //验证表单是否有效
        var bootstrapValidator = $('#articleForm').data('bootstrapValidator');
        //手动触发验证
        bootstrapValidator.validate();
        if(!bootstrapValidator.isValid())
            return;
        if(categoryId.length==0){
            alert("请选择分类！")
            return;
        }else if(tagIds.length==1){
            alert("请选择标签！")
            return;
        }else if(CKEDITOR.instances.TextArea1.getData().length==0){
            alert("请输入文章的内容！")
            return;
        }
        $.post("${draftUrl}",
            {
                articleId: $("#articleId").val(),
                summary: $('#summary').val(),
                title: $('#title').val(),
                categoryId: categoryId,
                tagIds: tagIds,
                content: CKEDITOR.instances.TextArea1.getData(),//TextArea1是放这个编辑器的标签的id
            },
            function (data) {
                data = $.parseJSON(data);
                alert(data.msg);
            });
    });
    //表单验证
    $('#articleForm').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },

        fields: {
            summary: {
                message: '名称验证失败',
                validators: {
                    notEmpty: {
                        message: '概述不能为空'
                    }
                }
            },
            title: {
                validators: {
                    notEmpty: {
                        message: '标题不能为空'
                    }
                }
            }
        }
    });
</script>

</body>
</html>
